<template>
  <ContentWrap>
    <div class="mb-10px routeHeader">
      <el-button
        @click="submitForm(2)"
        type="primary"
        :disabled="formLoading"
        v-hasPermi="['order:marketing-order-alter:handle']"
        >提交</el-button
      >
      <el-button @click="close">关闭</el-button>
    </div>
    <el-scrollbar :max-height="`${contentHeight - 73}px`">
      <!-- 订单表单 -->
      <el-table border v-loading="formLoading" ref="orderTableRef" :data="formData">
        <el-table-column
          v-for="(item, index) in orderTableTitleList"
          :key="index"
          :label="item.label"
          :header-align="item.headerAlign"
          :align="item.align"
          :prop="item.field"
          min-width="200px"
        >
          <template #default="scope">
            <!-- 合同日期 订单日期 -->
            <el-date-picker
              v-if="['contractDate', 'orderDate'].includes(item.field)"
              v-model="scope.row[item.field]"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder=""
              style="width: 100%"
            />
            <el-input
              v-else-if="['salesperson', 'paymentConditions', 'remark'].includes(item.field)"
              v-model="scope.row[item.field]"
            />
            <el-input-number
              v-else-if="['taxRate', 'exchangeRate'].includes(item.field)"
              :min="0"
              v-model="scope.row[item.field]"
            />
            <template v-else-if="item.field === 'orderNumber'">
              <!-- 订单号 -->
              <el-select
                v-model="orderNumberObj"
                value-key="id"
                filterable
                remote
                :remote-method="getOrderNumberList"
                :loading="orderNumberLoading"
                style="width: 100%"
                @change="changeOrderNumber"
                :disabled="formType === 'update'"
              >
                <el-option
                  v-for="item in orderNumberList"
                  :key="item['id']"
                  :label="item.orderNumber"
                  :value="item"
                />
              </el-select>
            </template>
            <!-- 商务合同 -->
            <template v-else-if="item.field === 'fileName'">
              <el-button
                v-if="formType === 'update'"
                link
                type="primary"
                @click="openFile(scope.row.filePath)"
              >
                {{ scope.row.fileName }}
              </el-button>
              <UploadFile
                v-else
                v-model="scope.row.fileList"
                :isShowTip="false"
                :limit="1"
                :fileSize="200"
                :fileType="['pdf', 'png', 'jpg']"
                @update:modelValue="uploadFile"
              />
            </template>
            <template v-else>
              <!-- 字典翻译 -->
              <dict-tag v-if="item.dictType" :type="item.dictType" :value="scope.row[item.field]" />
              <div v-else>{{ scope.row[item.field] }}</div>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-button class="mt-10px mb-10px" type="primary" @click="createRow">新增行</el-button>
      <!-- 产品表单 -->
      <el-table border v-loading="formLoading" ref="orderTableRef" :data="products">
        <el-table-column type="index" label="序号" width="50px" align="center" />
        <el-table-column
          v-for="(item, index) in productTableTitleList"
          :key="index"
          :label="item.label"
          :header-align="item.headerAlign"
          :align="item.align"
          :prop="item.field"
          min-width="200px"
        >
          <template #default="scope">
            <!-- 发货日期 -->
            <el-date-picker
              v-if="['deliveryDate'].includes(item.field)"
              v-model="scope.row[item.field]"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder=""
              style="width: 100%"
              :disabled="![20, 70].includes(scope.row.dictChangeType)"
            />
            <!-- 订单数量 -->
            <el-input-number
              v-nextInput="'orderQuantity'"
              name="orderQuantity"
              v-else-if="['orderQuantity'].includes(item.field)"
              v-model="scope.row[item.field]"
              :min="0"
            />
            <!-- 报价 含税单价 价税合计 税率 -->
            <el-input-number
              v-nextInput="'priceTaxTotal'"
              name="priceTaxTotal"
              v-else-if="
                ['quotation', 'taxIncludedPrice', 'priceTaxTotal', 'taxRate'].includes(item.field)
              "
              v-model="scope.row[item.field]"
              :min="0"
              :disabled="![10, 70].includes(scope.row.dictChangeType)"
            />
            <el-input
              v-nextInput="'remark'"
              name="remark"
              v-else-if="['remark'].includes(item.field)"
              v-model="scope.row[item.field]"
            />
            <template v-else-if="item.field === 'productNumber'">
              <!-- 产品编号 -->
              <el-select
                v-model="scope.row.productNumber"
                filterable
                remote
                :remote-method="getProductNumberList"
                :loading="productNumberLoading"
                style="width: 100%"
                @change="changeProductNumber(scope.$index, scope.row.productNumber)"
              >
                <el-option
                  v-for="item in productNumberList"
                  :key="item['productNumber']"
                  :label="item['productNumber']"
                  :value="item['productNumber']"
                />
              </el-select>
            </template>
            <el-select
              v-else-if="['dictChangeType'].includes(item.field)"
              v-model="scope.row[item.field]"
              placeholder="请选择变更类型"
              :disabled="scope.row.isNew"
            >
              <el-option
                v-for="dict, index in getIntDictOptions('change_type')"
                :key="index"
                :label="dict.label"
                :value="dict.value"
                :disabled="dict.value === 70"
              />
            </el-select>
            <el-select
              v-else-if="['dictDeliveryProjectType'].includes(item.field)"
              v-model="scope.row[item.field]"
              placeholder="请选择交货项目类型"
            >
              <el-option
                v-for="dict, index in getIntDictOptions('delivery_project_type')"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <template v-else>
              <!-- 字典翻译 -->
              <dict-tag v-if="item.dictType" :type="item.dictType" :value="scope.row[item.field]" />
              <template v-else>
                <div v-if="['orderChangeDate'].includes(item.field)">{{
                  formatDate(scope.row[item.field])
                }}</div>
                <div v-else>{{ scope.row[item.field] }}</div>
              </template>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-button
              type="danger"
              link
              @click="handleDelete(scope.$index)"
              v-if="[30, 40, 50, 60, 70].includes(scope.row.dictChangeType)"
            >
              删除行
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
    
  </ContentWrap>
</template>
<script setup lang="ts">
import * as MarketingOrderAlterApi from '@/api/orderManagement/marketingManagement/marketingOrderAlter'
import * as ProductApi from '@/api/orderManagement/productRelation'
import { getIntDictOptions } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import { orderTableTitleList, productTableTitleList } from './tableTitle.data'

const message = useMessage() // 消息弹窗

defineProps({
  formType: {
    type: String,
    default: ''
  },
  contentHeight: {
    type: Number,
    default: 0
  }
})

const formLoading = ref(false)
interface DataType {
  submitFlag: number
  orderNumber: string
  dictOrderType: number
  dictBusinessType: number
  dictSaleType: number
  customerName: string
  customerCode: string
  salesDepartment: string
  contractDate: string
  orderDate: string
  salesperson: string
  taxRate: string
  exchangeRate: string
  paymentConditions: string
  dictChangeType: number
  fileName: string
  filePath: string
  fileList: []
  dictOrderStatus: number
  remark: string
  products: []
}
const formData = ref<DataType[]>([])
const products = ref<MarketingOrderAlterApi.MarketingOrderAlterProductVO[]>([])
const orderNumberLoading = ref(false) //订单号远程搜索加载
const orderNumberList = ref<DataType[]>([])
const orderNumberObj = ref<DataType>() //订单对象
const productNumberLoading = ref(false) //产品编号远程搜索加载
const productNumberList = ref([]) //产品列表

// 保存/提交
const submitForm = async (type: number) => {
  if (!formData.value[0].contractDate) {
    message.notifyError('合同日期不能为空')
    return
  }
  if (!formData.value[0].orderDate) {
    message.notifyError('订单日期不能为空')
    return
  }
  if (!formData.value[0].salesperson) {
    message.notifyError('业务员不能为空')
    return
  }
  if (!formData.value[0].taxRate) {
    message.notifyError('税率不能为空')
    return
  }
  if (!formData.value[0].exchangeRate) {
    message.notifyError('汇率不能为空')
    return
  }
  if (!formData.value[0].paymentConditions) {
    message.notifyError('付款条件不能为空')
    return
  }
  console.log(formData.value[0].filePath)
  if (!formData.value[0].filePath) {
    message.notifyError('商务合同不能为空')
    return
  }
  for (let i = 0; i < products.value.length; i++) {
    if (!products.value[i].orderQuantity) {
      message.notifyError('订单数量不能为空')
      return
    }
    if (!products.value[i].deliveryDate) {
      message.notifyError('发货日期不能为空')
      return
    }
    if (!products.value[i].dictChangeType) {
      message.notifyError('变更类型不能为空')
      return
    }
    if (!products.value[i].dictDeliveryProjectType) {
      message.notifyError('交货项目类型不能为空')
      return
    }
    if (!products.value[i].quotation) {
      message.notifyError('报价不能为空')
      return
    }
    if (!products.value[i].taxIncludedPrice) {
      message.notifyError('含税单价不能为空')
      return
    }
    if (!products.value[i].priceTaxTotal) {
      message.notifyError('价税合计不能为空')
      return
    }
    if (!products.value[i].taxRate) {
      message.notifyError('税率不能为空')
      return
    }
  }
  formData.value[0].submitFlag = type
  formLoading.value = true
  try {
    await MarketingOrderAlterApi.createMarketingOrderAlter(formData.value[0])
    close()
  } finally {
    formLoading.value = false
  }
}

// 获取数据
const getData = async () => {
  formData.value = [
    {
      submitFlag: 1,
      orderNumber: '',
      dictOrderType: 0,
      dictBusinessType: 0,
      dictSaleType: 0,
      customerName: '',
      customerCode: '',
      salesDepartment: '',
      contractDate: '',
      orderDate: '',
      salesperson: '',
      taxRate: '',
      exchangeRate: '',
      paymentConditions: '',
      dictChangeType: 0,
      fileName: '',
      filePath: '',
      fileList: [],
      dictOrderStatus: 0,
      remark: '',
      products: []
    }
  ]
}

// 查看附件
const openFile = (url: string) => {
  window.open(url)
}

// 附件上传
const uploadFile = (data) => {
  const res = JSON.parse(data)
  if (res.length) {
    formData.value[0].fileName = res[0].name
    formData.value[0].filePath = res[0].url
  } else {
    formData.value[0].fileName = ''
    formData.value[0].filePath = ''
  }
}

// 获取订单列表
const getOrderNumberList = async (query: string) => {
  if (query) {
    orderNumberLoading.value = true
    try {
      const data = await MarketingOrderAlterApi.getMarketingOrderAlterOrderNumber({
        orderNumber: query
      })
      orderNumberList.value = data
    } finally {
      orderNumberLoading.value = false
    }
  } else {
    orderNumberList.value = []
  }
}

// 选择订单
const changeOrderNumber = async () => {
  const data = await MarketingOrderAlterApi.getMarketingOrderAlterRelationProduct(
    orderNumberObj.value?.orderNumber
  )
  data.fileList = []
  formData.value = [data]
  products.value = data.products
}

// 获取产品列表
const getProductNumberList = async (query: string) => {
  if (query) {
    productNumberLoading.value = true
    try {
      const data = await ProductApi.getProductsList({ productNumber: query })
      productNumberList.value = data.list
    } finally {
      productNumberLoading.value = false
    }
  } else {
    productNumberList.value = []
  }
}

// 选择产品
const changeProductNumber = async (index: number, productNumber: string) => {
  const data = await ProductApi.getProductsList({ productNumber: productNumber })
  products.value[index].productName = data.list[0].productName
  products.value[index].productStandard = data.list[0].productStandard
  products.value[index].partUnit = data.list[0].partUnit
}

// 新增行
const createRow = () => {
  products.value.push({
    productNumber: '',
    productName: '',
    productStandard: '',
    partUnit: '',
    orderQuantity: 0,
    deliveryDate: '',
    dictChangeType: 70,
    version: '',
    dictDeliveryProjectType: 1,
    quotation: 0,
    taxIncludedPrice: 0,
    priceTaxTotal: 0,
    taxRate: 0,
    dictStatus: 0,
    remark: '',
    orderChangePerson: '',
    orderChangeDate: '',
    isNew: true,
    isEdit: true
  })
}

// 删除行
const handleDelete = (index: number) => {
  products.value.splice(index, 1)
}

// 关闭
const emits = defineEmits(['goBack'])
const close = () => {
  emits('goBack')
}

onMounted(() => {
  getData()
})
</script>
